#! /usr/bin/env python

# Copyright (c) 2010, Arizona Robotics Research Group, University of Arizona
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the Willow Garage, Inc. nor the names of its
#       contributors may be used to endorse or promote products derived from
#       this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Matt Brockman
# Original Code: move_arm_demo.py & wubble_head_action.py by Ahn Tran
# I'm def. copying and pasting some of Ahn's methods instead of inheriting

PKG = 'manipulation_demos'
NAME = 'point_arm_demo'

#copied from move_arm_demo
import roslib; roslib.load_manifest(PKG)
import rospy
import tf

from actionlib import SimpleActionClient
from geometry_msgs.msg import PointStamped
from wubble_actions.msg import *
import math

class PointArmDemo():

    def __init__(self):
        rospy.init_node(NAME, anonymous=True)
        self.client = SimpleActionClient("smart_arm_action", SmartArmAction)
        self.client.wait_for_server()
        self.tf = tf.TransformListener()
        self.shoulder_pan_frame = 'arm_shoulder_pan_link'
        self.shoulder_tilt_frame = 'arm_shoulder_tilt_link'

    #(almost) blatent copy / past from wubble_head_action.py.  I should figure out how to inherit this wut!
    def transform_target_point(self, point):

        #see, 'shoulder' was 'head' in original.  the only change!
        pan_target_frame = self.shoulder_pan_frame
        tilt_target_frame = self.shoulder_tilt_frame
        
        # Wait for tf info (time-out in 5 seconds)
        self.tf.waitForTransform(pan_target_frame, point.header.frame_id, rospy.Time(), rospy.Duration(5.0))
        self.tf.waitForTransform(tilt_target_frame, point.header.frame_id, rospy.Time(), rospy.Duration(5.0))

        # Transform target point to pan reference frame & retrieve the pan angle
        pan_target = self.tf.transformPoint(pan_target_frame, point)
        pan_angle = math.atan2(pan_target.point.y, pan_target.point.x)
        #rospy.loginfo("%s: Pan transformed to <%s, %s, %s> => angle %s", \
        #        NAME, pan_target.point.x, pan_target.point.y, pan_target.point.z, pan_angle)

        # Transform target point to tilt reference frame & retrieve the tilt angle
        tilt_target = self.tf.transformPoint(tilt_target_frame, point)
        tilt_angle = math.atan2(tilt_target.point.z,
                math.sqrt(math.pow(tilt_target.point.x, 2) + math.pow(tilt_target.point.y, 2)))
        #rospy.loginfo("%s: Tilt transformed to <%s, %s, %s> => angle %s", \
        #        NAME, tilt_target.point.x, tilt_target.point.y, tilt_target.point.z, tilt_angle)

        return [pan_angle, tilt_angle]

    #point!  modified move_arm + reach_at from move_arm_demo
    def point_at(self, frame_id, x, y, z):

        goal = SmartArmGoal()
        goal.target_point = PointStamped()
        goal.target_point.header.frame_id = frame_id
        goal.target_point.point.x = x
        goal.target_point.point.y = y
        goal.target_point.point.z = z
        
        target_shoulder = list()
        target_shoulder = self.transform_target_point(goal.target_point)

        # Creates a goal to send to the action server.

        goal.target_joints = [target_shoulder[0], target_shoulder[1], 0, 0]

        # Sends the goal to the action server.
        self.client.send_goal(goal)

        # Waits for the server to finish performing the action.
        self.client.wait_for_goal_to_finish()

        # Return result
        return self.client.get_result()

    #copied from move_arm_demo
    def move_arm(self, shoulder_pan, shoulder_tilt, elbow_tilt, wrist_rotate):

        # Creates a goal to send to the action server.
        goal = SmartArmGoal()
        goal.target_joints = [shoulder_pan, shoulder_tilt, elbow_tilt, wrist_rotate]

        # Sends the goal to the action server.
        self.client.send_goal(goal)

        # Waits for the server to finish performing the action.
        self.client.wait_for_goal_to_finish()

        # Return result
        return self.client.get_result()


if __name__ == '__main__':
    try:
        pointle = PointArmDemo()
        print "Straighten arm"
        result = pointle.move_arm(0.0, 0.0, 0.0, 0.0);
        if result.success == False:
            print "Action failed"
        else:
            print "Result: [" + str(result.arm_position[0]) + ", " + str(result.arm_position[1]) + \
                str(result.arm_position[2]) + ", " + str(result.arm_position[3]) + "]"
        print "Point to point [0.2, -0.2, -0.02] from /arm_base_link"
        result = pointle.point_at("/arm_base_link", 0.2, -0.2, -0.02)
        if result.success == False:
            print "Action failed"
        else:
            print "Result: [" + str(result.arm_position[0]) + ", " + str(result.arm_position[1]) + \
                str(result.arm_position[2]) + ", " + str(result.arm_position[3]) + "]"

        print "Point to point [1, -5, 7] from /arm_base_link"
        result = pointle.point_at("/arm_base_link", 1, -5, 7)
        if result.success == False:
            print "Action failed"
        else:
            print "Result: [" + str(result.arm_position[0]) + ", " + str(result.arm_position[1]) + \
                str(result.arm_position[2]) + ", " + str(result.arm_position[3]) + "]"


    except rospy.ROSInterruptException:
        pass
